package com.myhome.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.myhome.domain.User;
import com.myhome.dto.BankDto;
import com.myhome.mappers.UserBankDtoMapper;
import com.myhome.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.myhome.mapper.UserBankMapper;
import com.myhome.domain.UserBank;
import com.myhome.service.UserBankService;

/**
 * @Author QYiXin
 * @Date 2021 10 13 10 51
 **/
@Service
public class UserBankServiceImpl extends ServiceImpl<UserBankMapper, UserBank> implements UserBankService {
    @Autowired
    UserService userService;

    @Override
    public Page<UserBank> getPagesBanks(Page<UserBank> page, Long userId) {
        return this.page(page, new LambdaQueryWrapper<UserBank>().eq(UserBank::getUserId, userId));
    }

    @Override
    public UserBank getCurrentUserBank(Long userId) {
        return this.getOne(new LambdaQueryWrapper<UserBank>()
                .eq(UserBank::getUserId, userId)
                .eq(UserBank::getStatus, (byte) (1)));

    }


    @Override
    public Boolean bindUserBank(Long userId, UserBank userBank) {
        User user = userService.getById(userId);
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if (!encoder.matches(userBank.getPayPassword(), user.getPaypassword())) {
            throw new IllegalArgumentException("交易密码错误");
        }
        Long id = userBank.getId();
        if (id != null) {
            //修改
            return this.updateById(userBank);
        } else {
            //新增
            userBank.setUserId(userId);
            return this.save(userBank);
        }
    }

    @Override
    public BankDto getSomeUserBankInfo(Long userId) {
        UserBank userBank = this.getOne(new LambdaQueryWrapper<UserBank>().eq(userId != null, UserBank::getUserId, userId));
        if (userBank != null) {
            return UserBankDtoMapper.INSTANCE.convert2Dto(userBank);
        }
        return null;
    }
}
